/**
 * 客户端测试1192排名接口脚本
 * 专注于测试：玩家高手榜、富豪榜、娱乐榜
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    }
};

class Code1192RankingTester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
    }

    async runTest() {
        console.log('🚀 开始1192排名接口测试...\n');

        try {
            await this.testHttpLogin();
            await this.testWebSocketConnection();
            await this.testQueryCharacters();

            if (this.characters.length === 0) {
                // await this.testCreateCharacter();
                await this.testQueryCharacters();
            }

            await this.testSelectCharacter();

            // 测试三种排名
            await this.testLevelRanking();
            await this.testWealthRanking();
            await this.testCasinoRanking();

            console.log('\n✅ 所有测试完成');

        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        } finally {
            if (this.ws) this.ws.close();
        }
    }

    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录...');
        try {
            await this.registerUser();
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;
                console.log(`✅ 登录成功: userId=${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }
        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            throw error;
        }
    }

    async registerUser() {
        try {
            await this.makeHttpRequest('/user-service/user/register', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash,
                captcha: '123456'
            });
            console.log('📝 用户注册成功');
        } catch (error) {
            if (error.message.includes('MOBILE_EXISTS') || error.message.includes('已存在')) {
                console.log('👤 用户已存在，跳过注册');
            } else {
                console.log('⚠️ 注册失败:', error.message);
            }
        }
    }

    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接...');
        return new Promise((resolve, reject) => {
            const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
            this.ws = new WebSocket(wsUrl);

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                this.setupMessageHandler();
                resolve();
            });

            this.ws.on('error', (error) => {
                console.log('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            setTimeout(() => {
                if (this.ws.readyState === WebSocket.CONNECTING) {
                    this.ws.close();
                    reject(new Error('连接超时'));
                }
            }, 10000);
        });
    }

    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));
                this.handleWebSocketResponse(message);
            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    handleWebSocketResponse(message) {
        const { act_id, code, roleList, roleCount } = message;
        switch (act_id) {
            case 3:
                if (roleList && Array.isArray(roleList)) {
                    this.characters = roleList;
                    console.log(`📋 获取到${roleCount || roleList.length}个角色`);
                }
                break;
            case 4:
                if (code === 0) console.log('🎯 角色选择成功');
                break;
            case 5:
            case 390:
                if (code === 0) console.log('🆕 角色创建成功');
                break;
            case 1192:
                this.handleRankingResponse(message);
                break;
        }
    }

    handleRankingResponse(message) {
        const { type, code, list, sum, more } = message;
        if (code === 0) {
            const typeNames = { 1: '玩家高手榜', 2: '富豪榜', 4: '娱乐榜' };
            const typeName = typeNames[type] || `类型${type}`;
            console.log(`\n🏆 ${typeName}数据接收成功:`);
            console.log(`   记录数: ${list ? list.length : 0}`);
            console.log(`   总记录数: ${sum || 0}`);
            console.log(`   说明: ${more || '无'}`);

            if (list && list.length > 0) {
                console.log('   前3名记录:');
                list.slice(0, 3).forEach((item, index) => {
                    console.log(`     ${index + 1}. ${item.name} (ID: ${item.id}) - ${item.content}`);
                });
            }
        }
    }

    async testQueryCharacters() {
        console.log('\n📋 步骤3: 查询角色列表...');
        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                resolve();
                return;
            }

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);
                        if (message.roleList && Array.isArray(message.roleList)) {
                            this.characters = message.roleList;
                            console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
                        } else {
                            this.characters = [];
                            console.log('✅ 查询成功，暂无角色');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({ c: 3, d: null }));

            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                resolve();
            }, 10000);
        });
    }

    async testCreateCharacter() {
        console.log('\n🆕 步骤4: 创建角色...');
        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                resolve();
                return;
            }

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 5 || message.act_id === 390) {
                        this.ws.removeListener('message', responseHandler);
                        if (message.code === 0) {
                            console.log('✅ 角色创建成功');
                            setTimeout(resolve, 2000);
                        } else {
                            console.log(`❌ 角色创建失败: ${message.msg || '未知错误'}`);
                            resolve();
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 5,
                d: {
                    name: `测试角色_${Date.now()}`,
                    sex: 1,
                    roleType: 1,
                    headIndex: 2
                }
            }));

            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                resolve();
            }, 15000);
        });
    }

    async testSelectCharacter() {
        console.log('\n🎯 步骤5: 选择角色...');
        if (this.characters.length === 0) {
            console.log('⚠️ 没有可选择的角色');
            return;
        }

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                resolve();
                return;
            }

            const targetCharacter = this.characters[0];
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 4) {
                        this.ws.removeListener('message', responseHandler);
                        if (message.code === 0) {
                            console.log(`✅ 角色选择成功: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
                            setTimeout(resolve, 2000);
                        } else {
                            console.log(`❌ 角色选择失败: ${message.msg || '未知错误'}`);
                            resolve();
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 4,
                d: { characterId: targetCharacter.id }
            }));

            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                resolve();
            }, 10000);
        });
    }

    async testLevelRanking() {
        console.log('\n🏆 步骤6: 测试玩家高手榜 (type=1)...');
        return this.sendRankingRequest(1, '玩家高手榜');
    }

    async testWealthRanking() {
        console.log('\n💰 步骤7: 测试富豪榜 (type=2)...');
        return this.sendRankingRequest(2, '富豪榜');
    }

    async testCasinoRanking() {
        console.log('\n🎰 步骤8: 测试娱乐榜 (type=4)...');
        return this.sendRankingRequest(4, '娱乐榜');
    }

    async sendRankingRequest(type, typeName) {
        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                resolve();
                return;
            }

            let responseReceived = false;
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    console.log('📤 收到消息:', JSON.stringify(message, null, 2));
                    if (message.act_id === 1192 && message.type === type) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            const requestData = {
                c: 1192,
                d: { type, myrate: 0, pageNum: 0 }
            };

            console.log(`📤 发送${typeName}请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            }, 10000);
        });
    }

    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: { 'Content-Type': 'application/json' }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, (res) => {
                let body = '';
                res.on('data', (chunk) => { body += chunk; });
                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => reject(error));
            if (data) req.write(JSON.stringify(data));
            req.end();
        });
    }
}

// 运行测试
async function main() {
    const tester = new Code1192RankingTester();
    await tester.runTest();
}

if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = Code1192RankingTester;
